package com.banciyuan.bcywebview.base.view.space;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.banciyuan.bcywebview.R;

/**
 * Created by squall on 2016/5/10.
 */
public class Space extends View {

    private int shadow_height;
    private int shadow_color;
    private int space_color;
    private int width;
    private int height;
    private Paint space_paint;
    private Paint shadow_paint;

    public Space(Context context) {
        super(context);
        initPaint();
    }

    public Space(Context context, AttributeSet attrs) {
        super(context, attrs);
        getAttr(context, attrs);
        initPaint();
    }

    public Space(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getAttr(context, attrs);
        initPaint();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public Space(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        getAttr(context, attrs);
        initPaint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRect(0, 0, width, height, space_paint);
        canvas.drawRect(0, 0, width, shadow_height, shadow_paint);
    }

    private void initPaint() {
        space_paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        space_paint.setStyle(Paint.Style.FILL);
        space_paint.setColor(space_color);

        shadow_paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        shadow_paint.setStyle(Paint.Style.FILL);
        LinearGradient lg = new LinearGradient(0f, 0f, 0f, 4f, getResources().getColor(R.color.gray_10), getResources().getColor(R.color.transparent), Shader.TileMode.MIRROR);
        shadow_paint.setShader(lg);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingRight() - getPaddingLeft();
        height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom();
    }

    private void getAttr(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Space);
        shadow_height = (int) a.getDimension(R.styleable.Space_shadow_height, 4);
        space_color = a.getColor(R.styleable.Space_space_color, getResources().getColor(R.color.background));
        shadow_color = a.getColor(R.styleable.Space_shadow_color, getResources().getColor(R.color.block_line));
        a.recycle();
    }
}
